package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Repository;

import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.DateTimeUtil;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.Mail;
import com.fsd.core.util.ParametersUtil;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.B_leaveword;
import com.fsd.admin.model.F_flowdealt;
import com.fsd.admin.model.F_flownode;
import com.fsd.admin.model.F_flownodeterm;
import com.fsd.admin.model.F_flowrecord;
import com.fsd.admin.service.A_EmployeeService;
import com.fsd.admin.service.B_leavewordService;
import com.fsd.admin.service.F_flowWorkService;
import com.fsd.admin.dao.B_leavewordDao;
import com.fsd.admin.entity.A_LoginInfo;
import com.google.gson.Gson;

@Repository("b_leavewordServiceImpl")
public class B_leavewordServiceImpl extends WorkFlowServiceImpl<B_leaveword, String> implements B_leavewordService{
    
    private static final Logger log = Logger.getLogger(B_leavewordServiceImpl.class);
    private String depict = "留言信息";
    
    @Resource(name = "b_leavewordDaoImpl")
	public void setBaseDao(B_leavewordDao b_leavewordDao) {
		super.setBaseDao(b_leavewordDao);
	}
	
	@Resource(name = "b_leavewordDaoImpl")
	private B_leavewordDao objectDao;

    @Resource(name = "A_EmployeeServiceImpl")
	private A_EmployeeService employeeService;
    
	/**
     * 流程编码前缀
     */
	public static final String flowCode = "leaveword";

	//信箱类型
	/**
	 * 普通留言板
	 */
	public static final String lybpt1 = "lybpt";
	public static final String lybpt2 = "普通留言板";
	/**
	 * 在线咨询
	 */
	public static final String lybzx1 = "lybzx";
	public static final String lybzx2 = "在线咨询";
	/**
	 * 领导信箱
	 */
	public static final String lybld1 = "lybld";
	public static final String lybld2 = "领导信箱";
	/**
	 * 信访信箱
	 */
	public static final String lybxf1 = "lybxf";
	public static final String lybxf2 = "信访信箱";
	/**
	 * 举报信箱
	 */
	public static final String lybjb1 = "lybjb";
	public static final String lybjb2 = "举报信箱";
	/**
	 * 纪检监察
	 */
	public static final String lybjj1 = "lybjj";
	public static final String lybjj2 = "纪检监察";
	/**
	 * 政务公开意见箱
	 */
	public static final String lybgkyj1 = "lybgkyj";
	public static final String lybgkyj2 = "政务公开意见箱";
	/**
	 * 民意征集
	 */
	public static final String lybmy1 = "lybmy";
	public static final String lybmy2 = "民意征集";
	/**
	 * 矿产举报
	 */
	public static final String lybkc1 = "lybkc";
	public static final String lybkc2 = "矿产违法举报";
	/**
	 * 土地举报
	 */
	public static final String lybtd1 = "lybtd";
	public static final String lybtd2 = "土地违法举报";
	/**
	 * 巡查信箱
	 */
	public static final String lybxc1 = "lybxc";
	public static final String lybxc2 = "巡查信箱";
	/**
	 * 群众路线意见箱
	 */
	public static final String lybqzyj1 = "lybqzyj";
	public static final String lybqzyj2 = "群众路线意见箱";
	
	/**
	 * 退回到流程申请人调用
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowBackOriginal(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 撤回到流程申请人调用
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowRecallOriginal(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 开始流程调用数据对象处理
	 * @param dataobjectid
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowStart(String dataobjectid, String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + dataobjectid + "'");
	}
	
	/**
	 * 终止流程调用数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowStop(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 完成流程调用数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowFinish(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 保存当前流程节点数据对象处理
	 * @param record
	 * @param flowDealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public void saveWorkFlowNodeDealt(F_flowrecord record, F_flowdealt flowDealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
	}
	
	/**
	 * 自动流程节点数据对象处理
	 * @param record
	 * @param dealt
	 * @param term
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAuto(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		objectDao.executeHql("update B_leaveword t set t.flowstatus = '" + dataStatus + "', " +
				" t.flowstatusname = '" + dataStatusName + "' " +
				" where t.id = '" + record.getDataobjectid() + "'");
		return true;
	}
	
	/**
	 * 自动流程节点数据对象处理
	 * @param record
	 * @param dealt
	 * @param term
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @throws Exception
	 */
	public String saveWorkFlowNodeAutoValue(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		return null;
	}

	/**
	 * 自动流程节点数据选择单一对象处理
	 * @param record
	 * @param dealt
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @return
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAutoChooseSingle(F_flowrecord record, F_flowdealt dealt, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		B_leaveword obj = this.objectDao.get(record.getDataobjectid());
		if (dealt.getValueinfo().equals("FSDDELETE")){
			obj.setDeleted("1");
		}else{
			obj.setAddemployeeid(dealt.getValueinfo());
			obj.setAddemployeename(dealt.getValuedepict());
			obj.setDeleted("0");
			A_Employee empObj = this.employeeService.get(dealt.getValueinfo());
			this.sendMail(obj, empObj);
		}
		obj.setIsreply("false");
		obj.setAuditing("false");
		obj.setFlowstatus(dataStatus);
		obj.setFlowstatusname(dataStatusName);
		this.objectDao.update(obj);
		return true;
	}
	
	/**
	 * 自动流程节点数据选择多对象处理
	 * @param record
	 * @param dealtList
	 * @param dataStatus
	 * @param dataStatusName
	 * @param loginInfo
	 * @return
	 * @throws Exception
	 */
	public boolean saveWorkFlowNodeAutoChooseMulti(F_flowrecord record, List<F_flowdealt> dealtList, 
			String dataStatus, String dataStatusName, A_LoginInfo loginInfo) throws Exception{
		return true;
	}
	
	
	private void sendMail(B_leaveword leaveobj, A_Employee empObj){
		if(empObj.getEmail() != null && !"".equals(empObj.getEmail())){
			//发送邮件开始
			String smtp = "smtp.qq.com";//SMTP服务器
	    	String from = "1438619547@qq.com";//发信人
	    	String username="1438619547@qq.com";//用户名
	    	String password="gsdlr2015/07/06";//密码
	    	String to = empObj.getEmail();//收信人
	    	String subject = "甘肃省国土资源厅门户网站-受理回复提醒";//邮件主题
	    	//邮件内容
	    	String content = "甘肃省国土资源厅门户网站后台<br />“" + leaveobj.getTypename() + 
	    			"”受理，有您需要处理的回复信息！<br/><br/>甘肃省国土资源厅门户网站&nbsp;<a target='_blank' href='http://www.gsdlr.gov.cn/admin'>后台登录</a>";
	    	Mail.send(smtp, from, to, subject, content, username, password);
	    	//发送邮件结束
		}
	}
	
	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("submitdate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				c.add(Restrictions.eq("type", objectMap.get("fid")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("name") + "%"));
			}
			if(objectMap.get("isreply") != null && !"".equals(objectMap.get("isreply"))){
				c.add(Restrictions.eq("isreply", objectMap.get("isreply")));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	/**
	 * 加载分页数据，加载所属回复人数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListByEmployee(ParametersUtil param, A_LoginInfo loginInfo) throws Exception{
		A_Employee employee = loginInfo.getEmployee();
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("submitdate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("fid") != null && !"".equals(objectMap.get("fid"))){
				if (!employee.isIsadmin()){
					if(objectMap.get("glqx") != null && !"".equals(objectMap.get("glqx"))){
						if (!this.checkPopedom(objectMap.get("glqx").toString(), Config.POPEDOMMEUN, loginInfo.getPopedomMap())){
							c.add(Restrictions.eq("addemployeeid", employee.getId()));
						}
					}
				}
				c.add(Restrictions.eq("type", objectMap.get("fid")));
			}
			if(objectMap.get("isreply") != null && !"".equals(objectMap.get("isreply"))){
				c.add(Restrictions.eq("isreply", objectMap.get("isreply")));
			}
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}
	
	
	/**
	 * 加载回收站分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageListRecycle(ParametersUtil param, A_Employee employee) throws Exception{
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "1"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.addOrder(Order.desc("submitdate"));
		if(param.getJsonData() != null && !"".equals(param.getJsonData())){
			Gson gs = new Gson();
			Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
			if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
				c.add(Restrictions.like("title", "%" + objectMap.get("name") + "%"));
			}
		}
		return objectDao.findPager(param , c);
	}

	/**
	 * 保存角色
	 * @param popedomgroup
	 * @throws Exception
	 */
	public void saveObject(B_leaveword obj, A_LoginInfo loginInfo) throws Exception{
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			B_leaveword obj_old = objectDao.get(obj.getId());
			if (obj_old != null){
				obj_old.setAtitle(obj.getAtitle());
				obj_old.setAcontent(obj.getAcontent());
				if (obj_old.getIsreply() != null && obj_old.getIsreply().equals("true")){
					obj_old.setIsreply("true");
					obj_old.setUpdatedate(this.getData());//设置修改日期
					obj_old.setUpdateemployeeid(loginInfo.getEmployee().getId());//设置修改用户id
					obj_old.setUpdateemployeename(loginInfo.getEmployee().getRealname());//设置修改用户姓名
				}else{
					obj_old.setIsreply("true");
					obj_old.setAbranchid(loginInfo.getEmployee().getBranchid());
					obj_old.setAbranchname(loginInfo.getEmployee().getBranchname());
					if (obj.getAdddate() != null && !obj.getAdddate().equals("")){
						obj_old.setAdddate(DateTimeUtil.checkDateTime14(obj.getAdddate()));
					}else{
						obj_old.setAdddate(this.getData());//设置添加日期
					}
					obj_old.setAddemployeeid(loginInfo.getEmployee().getId());//设置添加用户id
					obj_old.setAddemployeename(loginInfo.getEmployee().getRealname());//设置添加用户姓名
				}
				obj_old.setAuditing("false");
				objectDao.update(obj_old);
			}
		}else{
			//添加
			obj.setId(this.getUUID());
			obj.setCompanyid(loginInfo.getEmployee().getCompanyid());
			obj.setSubmitdate(this.getData());
			obj.setDeleted("0");
			obj.setAuditing("false");
			obj.setFlowstatus(sjds1);
			obj.setFlowstatusname(sjds2);
			objectDao.save(obj);
			Map<String, Object> mapJson = new HashMap<String, Object>();
			mapJson.put("data", obj);
			this.saveWorkFlowSubmit(flowCode + obj.getType(), obj.getId(), 
					obj.getType(), obj.getTypename(), obj.getQureycode(), 
					obj.getName() + "；" + obj.getTitle(), mapJson, loginInfo, true);
		}
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), loginInfo.getEmployee(), B_leavewordServiceImpl.class);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public B_leaveword getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		B_leaveword obj = objectDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		return obj;
	}
	
	/**
	 * 删除对象
	 * @param parameters
	 * @throws Exception
	 */
	public void delObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_leaveword t set t.deleted = '1' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPESC, this.depict + ids, employee, B_leavewordServiceImpl.class);
	}
	
	/**
	 * 审核对象
	 * @param parameters
	 * @throws Exception
	 */
	public void auditObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String status = objectMap.get("status").toString();
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_leaveword t set t.auditing = '"+ status +"' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPEQT, this.depict + "修改审核状态" + status + ",ID集合" + ids, employee, B_leavewordServiceImpl.class);
	}
	
	/**
	 * 选登对象
	 * @param parameters 
	 * @throws Exception
	 */
	public void chooseObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String status = objectMap.get("status").toString();
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_leaveword t set t.selected = '"+ status +"' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPEQT, this.depict + "修改选登状态" + status + ",ID集合" + ids, employee, B_leavewordServiceImpl.class);
	}
	
	/**
	 * 恢复对象
	 * @param parameters 
	 * @throws Exception
	 */
	public void recycleObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_leaveword t set t.deleted = '0' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPEQT, this.depict + "恢复删除信息" + ids, employee, B_leavewordServiceImpl.class);
	}
	

	/**
	 * 加载回收站分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public void saveDealtObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		Criteria c = objectDao.createCriteria();
		c.add(Restrictions.eq("deleted", "0"));
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("id", objectMap.get("id")));
		List<B_leaveword> objList = objectDao.getList(c);
		if(objList == null || objList.size() == 0){
			throw new BusinessException(depict + "未找到要处理的数据!");
		}
		for (B_leaveword obj : objList) {
			if ("true".equals(obj.getIsreply()))
				throw new BusinessException(depict + "数据已回复!");
			if (obj.getAddemployeeid() != null && !"".equals(obj.getAddemployeeid()))
				throw new BusinessException(depict + "数据已有回复人!");
			Map<String, Object> mapJson = new HashMap<String, Object>();
			mapJson.put("data", obj);
			this.saveWorkFlowSubmit(flowCode + obj.getType(), obj.getId(), 
					obj.getType(), obj.getTypename(), obj.getQureycode(), 
					obj.getName() + "；" + obj.getTitle(), mapJson, 
					employee.getCompanyid(), obj.getName(), true);
		}
	}
	
	/**
	 * 变更回复人
	 * @param parameters 
	 * @throws Exception
	 */
	public void hfrbgObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(dir);
		String empid = objectMap.get("empid").toString();
		A_Employee empObj = this.employeeService.get(empid);
		if (empObj == null){
			throw new BusinessException(depict + "变更回复人未找到!");
		}
		objectDao.executeHql("update B_leaveword t set t.addemployeeid = '" + empObj.getId() + 
				"', t.addemployeename = '" + empObj.getRealname() + "' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPEQT, this.depict + "变更回复人" + empObj.getId() + empObj.getRealname() + ",ID集合" + ids, employee, B_leavewordServiceImpl.class);
		B_leaveword obj = this.objectDao.get(dir.get(0));
		if (obj != null){
			this.sendMail(obj, empObj);
		}
	}
	
	/**
	 * 敏感标志
	 * @param parameters 
	 * @throws Exception
	 */
	public void flageObject(ParametersUtil parameters, A_Employee employee) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String flage = objectMap.get("flage").toString();
		String ids = this.getSQLinByIDList(dir);
		objectDao.executeHql("update B_leaveword t set t.isflage = '"+ flage +"' where t.id in (" + ids + ")");
		this.sysLogService.saveObject(Config.LOGTYPEMGSZ, this.depict + "设置敏感标志状态" + flage + ",ID集合" + ids, employee, B_leavewordServiceImpl.class);
	}
}
